﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using A2DFramework.EventService.DistributeEventBus;

namespace A2DFramework.EventService.DistributeEventBus.Server.Commands
{
    public class Publish : CommandBase<EventDispatcherBusSession, StringRequestInfo>
    {
        public override void ExecuteCommand(EventDispatcherBusSession session, StringRequestInfo requestInfo)
        {
            string evtClassPath = Helper.RestoreSpecialCharacters(requestInfo.Parameters[0]);
            string evtXml = Helper.RestoreSpecialCharacters(requestInfo.Parameters[1]);

            foreach(EventDispatcherBusSession s in session.AppServer.GetAllSessions())
            {
                if (!s.Connected)
                    continue;

                if (s.AssociatedServerIdentity == session.AssociatedServerIdentity)
                    continue;

                if (s.SubscribedEventClasses.Contains(evtClassPath))
                {
                    s.Send("Publish " + requestInfo.Body);//forward only
                    Console.WriteLine(string.Format("Forwarding publish command from {1} to server: [{0}]", s.AssociatedServerIdentity, session.AssociatedServerIdentity));
                }
            }
        }
    }
}
